package com.gelpag.base.business.menu;

import been.UserInfo;
import com.gelpag.base.business.bean.PageBean;
import com.gelpag.base.business.common.CommonBase;
import com.gelpag.base.exception.VueException;
import com.gelpag.base.init.InitRedisService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import entity.Const;
import entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import tools.utils.Common;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    MenuService menuService;

    @Autowired
    InitRedisService initRedisService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    Logger logger = LoggerFactory.getLogger(MenuController.class);

    @PostMapping("/getMenuListByRoles")
    public Result getMenuListByRoles(HttpServletRequest request, String sys_code) {

        String token = request.getHeader("token");
        try {
            UserInfo userInfo = CommonBase.getUserInFromToken(token);

            if (userInfo == null) {
                return new Result(Const.RESULT_F1, Const.ERROR_MSG_F1, token,"");
            }

            List<MenuInfo> menuList = menuService.getMenuListByRoles(userInfo, sys_code);
            return new Result(Const.RESULT_0, "查询成功！",token,menuList);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Const.RESULT_1, "查询失败！",token,"");

        }
    }

    @PostMapping("/getMenuTree")
    public Result getMenuTree(HttpServletRequest request, String sys_code) {

        String token = request.getHeader("token");

        try {
            List<MenuInfo> menuInfoList = menuService.getMenuTree(sys_code);
            //添加根目录
            MenuInfo info = new MenuInfo();
            info.setMenu_name("根目录");
            info.setMenu_id("0000");
            info.setChildlist(menuInfoList);
            List<MenuInfo> list = new ArrayList<MenuInfo>();
            list.add(info);

            return new Result(Const.RESULT_0, "查询成功！", token, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Const.RESULT_0, "查询失败！", token, "");
        }
    }

    @PostMapping("/editMenu")
    public Result editMenu(HttpServletRequest request, MenuInfo menuInfo) {

        String token = request.getHeader("token");
        //参数验证
        Map<String, String> checkMap = isPassEditMenu(menuInfo);
        if (Const.NOT_NOMAL_PARAM.equals(checkMap.get(Const.PARAM_KEY))) {
            return new Result(Const.RESULT_1,checkMap.get(Const.PARAM_RET_KEY),token,"");
        }

        try {
            menuService.editMenu(menuInfo);
            //刷新redis缓存
            initRedisService.initRedis(stringRedisTemplate);
            return new Result(Const.RESULT_0, "保存成功！",token, "");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Const.RESULT_1, "保存失败！",token, "");
        }
    }

    private Map<String, String> isPassEditMenu(MenuInfo menuInfo) {

        Map<String, String> checkMap = new HashMap<String, String>();
        //默认返回正常
        checkMap.put(Const.PARAM_KEY,Const.NOMAL_PARAM);
        //验证menu_name是否为空
        if (Common.isNullString(menuInfo.getMenu_name())) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "菜单名称必须填写！");
            return checkMap;
        }
        //验证父节点id是否为空
        if (Common.isNullString(menuInfo.getParent_menu_id())) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "父节点id不能为空！");
            return checkMap;
        }
        //验证排序不能为空
        if (Common.isNullString(menuInfo.getSeq_num())) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "排序不能为空！");
            return checkMap;
        }
        if (Common.isNullString(menuInfo.getSys_code())) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "请选择一个系统！");
            return checkMap;
        }
        int count = menuService.getResourceCountByParent_menu_id(menuInfo.getParent_menu_id());
        if(count>0) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY,"父菜单下有url，不能在建子菜单！");
            return checkMap;
        }
        return checkMap;
    }

    @PostMapping("/getMenuInfoById")
    public Result getMenuInfoById(HttpServletRequest request, String menu_id) {
        String token = request.getHeader("token");
        try {
            //参数验证
            Map<String, String> checkMap = isPassGetMenuInfoById(menu_id);
            if (Const.NOT_NOMAL_PARAM.equals(checkMap.get(Const.PARAM_KEY))) {
                throw new VueException(Const.RESULT_1, checkMap.get(Const.PARAM_RET_KEY), token);
            }
            MenuInfo menuInfo = menuService.getMenuInfoById(menu_id);
            return new Result(Const.RESULT_0, "查询成功！",token,menuInfo);
        } catch(Exception e) {
            return new Result(Const.RESULT_1,"查询失败！",token, "");
        }
    }
    private Map<String, String> isPassGetMenuInfoById(String menu_id) {
        Map<String, String> checkMap = new HashMap<>();
        //默认返回正常
        checkMap.put(Const.PARAM_KEY, Const.NOMAL_PARAM);
        //验证menu_id不能为空
        if (Common.isNullString(menu_id)) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "menu_id不能为空");
            return checkMap;
        }
        return checkMap;
    }

    @PostMapping("/delMenu")
    public Result delMenu(HttpServletRequest request, String menu_id) {
        String token = request.getHeader("token");
        //参数验证
        Map<String, String> checkMap = isPassDelMenu(menu_id);
        if (Const.NOT_NOMAL_PARAM.equals(checkMap.get(Const.PARAM_KEY))) {
//            throw new VueException(Const.RESULT_1, checkMap.get(Const.PARAM_RET_KEY), token);
            return new Result(Const.RESULT_1, checkMap.get(Const.PARAM_RET_KEY), token, "");
        }
        try {
            menuService.delMenu(menu_id);
            return new Result(Const.RESULT_0, "删除成功！",token,"");
        } catch(Exception e) {
            e.printStackTrace();
            return new Result(Const.RESULT_1, "删除失败！",token,"");
        }
    }

    private Map<String, String> isPassDelMenu(String menu_id) {

        Map<String, String> checkMap = new HashMap<String, String>();
        //默认返回正常
        checkMap.put(Const.PARAM_KEY, Const.NOMAL_PARAM);
        if (Common.isNullString(menu_id)) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "menu_id不能为空");
            return checkMap;
        }
        //验证此菜单下是否还有子菜单
        List<MenuInfo> childMenus = menuService.getChildMenus(menu_id);
        if (childMenus.size()>0) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "此菜单下还有子菜单，请先删除子菜单！");
            return checkMap;
        }
        return checkMap;
    }

    /*
    * 根据菜单id获得菜单下的url列表
    * */
    @PostMapping("/getUrlsByMenuId")
    public Result getUrlsByMenuId(HttpServletRequest request, MenuInfo menuInfo) {

        String token = request.getHeader("token");
        //参数验证
        Map<String, String> checkMap = isPassGetUrlByMenuId(menuInfo.getMenu_id());
        if (Const.NOT_NOMAL_PARAM.equals(checkMap.get(Const.PARAM_KEY))) {
//            throw new VueException(Const.RESULT_1,checkMap.get(Const.PARAM_RET_KEY), token);
            return new Result(Const.RESULT_1,checkMap.get(Const.PARAM_RET_KEY),token,"");
        }

        try {
            int pageNum = Common.getPageNum(menuInfo.getPageNum());
            int pageSize = Common.getPageSize(menuInfo.getPageSize());
            Page<ResourceInfo> page = PageHelper.startPage(pageNum, pageSize);
            menuService.getUrlsByMenuId(menuInfo.getMenu_id());
            PageBean<ResourceInfo> pageData = new PageBean<>(pageNum, pageSize, page.getTotal(), page.getPages(), page.getResult());
            return new Result(Const.RESULT_0,"查询成功",token,pageData);
        } catch(Exception e) {
            e.printStackTrace();
            return new Result(Const.RESULT_1,"查询失败",token,"");
        }
    }
    private Map<String, String> isPassGetUrlByMenuId(String menu_id) {
        Map<String, String> checkMap = new HashMap<String, String>();
        //默认返回正常
        checkMap.put(Const.PARAM_KEY, Const.NOMAL_PARAM);
        if (Common.isNullString(menu_id)) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "menu_id 必须填写！");
            return checkMap;
        }
        return checkMap;
    }

    /**
     * 新增修改url
     * @param request
     * @param
     * @return
     */
    @PostMapping("/editUrl")
    public Result editUrl(HttpServletRequest request, ResourceInfo resourceInfo) {

        String token = request.getHeader("token");;
        //参数验证
        Map<String, String> checkMap = isPassGetMenuById(resourceInfo.getMenu_id());

        if (Const.NOT_NOMAL_PARAM.equals(checkMap.get(Const.PARAM_KEY))) {
            return new Result(Const.RESULT_1,checkMap.get(Const.PARAM_RET_KEY),token,"");
        }

        try {
            UserInfo userInfo = CommonBase.getUserInFromToken(token);
            if (userInfo == null) {
                return new Result(Const.RESULT_F1,"token过期！",token, "");
            }

            menuService.editUrl(resourceInfo, userInfo);
            initRedisService.initRedis(stringRedisTemplate);
            return new Result(Const.RESULT_0, "成功！",token,"");
        } catch (Exception e) {
            return new Result(Const.RESULT_1,"失败！",token,"");
        }
    }

    private Map<String, String> isPassGetMenuById(String menu_id) {

        Map<String, String> checkMap = new HashMap<String, String>();
        //默认返回正常
        checkMap.put(Const.PARAM_KEY, Const.NOMAL_PARAM);
        if (Common.isNullString(menu_id)) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "menu_id不能为空！");
            return checkMap;
        }
        //验证url是否为空，有子菜单的路由不能添加url
        int count = menuService.getChildMenusByMenuId(menu_id);
        if (count>0) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "此菜单下有子菜单，不能在其下面建url！");
            return checkMap;
        }
        return checkMap;
    }

    @PostMapping("/delUrl")
    public Result delUrl(HttpServletRequest request, ResourceInfo resourceInfo) {

        String token = request.getHeader("token");
        //参数验证
        Map<String, String> checkMap = isPassDelUrl(resourceInfo.getResource_id());
        if (Const.NOT_NOMAL_PARAM.equals(checkMap.get(Const.PARAM_KEY))) {
            return new Result(Const.RESULT_1,checkMap.get(Const.PARAM_RET_KEY),token,"");
        }
        try {
            menuService.delUrl(resourceInfo.getResource_id());
            return new Result(Const.RESULT_0,"删除成功！",token,"");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Const.RESULT_1,"删除失败！",token,"");
        }
    }

    private Map<String, String> isPassDelUrl(String resource_id) {

        Map<String, String> checkMap = new HashMap<>();

        //默认返回正常
        checkMap.put(Const.PARAM_KEY,Const.NOMAL_PARAM);
        if (Common.isNullString(resource_id)) {
            checkMap.put(Const.PARAM_KEY,Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY,"resource_id不能为空");
            return checkMap;
        }
        return checkMap;
    }
}
